<template>
  <div class="home_container">
    <!-- 导航栏start -->
    <nav-bar />
    <!-- 导航栏end -->

    <!-- tabs start -->
    <van-tabs :border="true">
      <van-tab
        :key="item.id"
        :title="item.name"
        v-for="item in channels"
      >
        <article-list :channel="item" />
      </van-tab>
    </van-tabs>
    <!-- tans end -->

    <!-- popup start  -->
    <channel-editor :myChannels="channels" />
    <!-- popup end -->
  </div>
</template>

<script>
import NavBar from "./chi-coms/nav-bar";
import ArticleList from "./chi-coms/article-list";
import ChannelEditor from "./chi-coms/channel-editor";
import { mapState } from "vuex";

import { getUserChannels } from "../../network/home";
import storage from "../../utils/storage";

export default {
  name: "Home",
  components: {
    NavBar,
    ArticleList,
    ChannelEditor
  },
  computed: {
    ...mapState(["USER_TOKEN"])
  },
  data() {
    return {
      channels: []
    };
  },
  created() {
    this.loadCurrentChannels();
  },
  methods: {
    //加载频道列表
    async loadCurrentChannels() {
      //判断是否登录，登录就发送请求获取
      if (this.USER_TOKEN) {
        const result = await getUserChannels();
        // console.log(result);
        if (result.message === "OK") {
          this.channels = result.data.channels;
        }
      } else {
        //没有登录从本地缓存中获取（有）
        if (storage.getItem("USER_CHANNELS")) {
          this.channels = storage.getItem("USER_CHANNELS");
        } else {//没有就发送请求获取
          const result = await getUserChannels();
          console.log(result);
          if (result.message === "OK") {
            this.channels = result.data.channels;
          }
        }
      }
    }
  }
};
</script>

<style scoped lang="stylus">
/deep/ .van-tab
  border-right 1px solid #edeff3

/deep/ .van-tabs__line
  background-color #3196fa
</style>